package com.it.park.controller.user;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.it.park.client.service.ArticleCollectService;
import com.it.park.client.service.IntegralIncomeService;
import com.it.park.client.service.SignInService;
import com.it.park.client.service.SignService;
import com.it.park.client.service.UserFriendService;
import com.it.park.common.JsonObj;
import com.it.park.common.MD5;
import com.it.park.constant.Constant;
import com.it.park.model.ArticleCollect;
import com.it.park.model.IntegralIncome;
import com.it.park.model.Sign;
import com.it.park.model.SignIn;
import com.it.park.model.UserFriend;
import com.it.park.rms.client.model.User;
import com.it.park.rms.client.service.UserService;
import com.it.park.util.file.FileUtil;

@Controller
@RequestMapping("/user")
public class UserController {
	private String rootPath=Constant.USER_PATH;
	@Autowired
	private UserService userService;
	@Autowired
	private ArticleCollectService articleCollectService;
	@Autowired
	private SignService signService;
	@Autowired
	private SignInService signInService;
	@Autowired
	private IntegralIncomeService incomeService;
	@Autowired
	private UserFriendService userFriendService;
	
	/**
	 * 收藏页面
	 */
	@RequestMapping("myCollect")
	public String myCollect(HttpSession session,HttpServletRequest request){
		User user = (User) session.getAttribute("user");
		List<ArticleCollect> collects =  articleCollectService.list(user.getId());//我的收藏
		request.setAttribute("collects", collects);
		return rootPath+"user/myCollect";
	} 
	
	/**
	 * 积分页面
	 */
	@RequestMapping("myIntegral")
	public String myIntegral(HttpSession session,HttpServletRequest request){
		return rootPath+"user/myIntegral";
	} 
	
	/**
	 *个人主页
	 */
	@RequestMapping("userIndex")
	public String userIndex(HttpSession session,HttpServletRequest request){
		User user = (User) session.getAttribute("user");
//		List<Notice> notices = noticeService.selectAll();//网站公告
//		request.setAttribute("notices", notices);
//		List<Link> linkLists = linkService.selectAll();//友情链接
//		request.setAttribute("linkLists", linkLists);
//		List<ArticleCollect> collects =  articleCollectService.list(user.getId());//我的收藏
//		request.setAttribute("collects", collects);
		Sign sign  = signService.selectLatestSign(user.getId());//我的动态
		request.setAttribute("sign", sign);
//		int total = msgService.getMsgTotal(user.getId());//未读消息数量
//		request.setAttribute("total", total);
		SignIn record = new SignIn();
		record.setUserId(user.getId());
		record.setCreateDate(new Date());
		SignIn signIn = signInService.selectByUserId(record);
		request.setAttribute("signIn", signIn);
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("type", 1);
		map.put("userId", user.getId());
		List<UserFriend> userFriends =  userFriendService.selectAllFriends(map);
		request.setAttribute("attention", userFriends.size());
		map.put("type", 2);
		userFriends =  userFriendService.selectAllFriends(map);
		request.setAttribute("attentionMe", userFriends.size());
		
		return rootPath+"userIndex";
	} 
	
	
	//177 6241 6141
	/**
	 *上传个人图像
	 */
	@RequestMapping("uploadPicture")
	public String uploadPicture(HttpSession httpSession,HttpServletRequest request){
	       
		return  rootPath+"user/uploadPersonPicture";
	}
	
	/**
	 *保存个人图像
	 */
	@RequestMapping("uploadPictureSave")
	public String uploadPictureSave(@RequestParam("picture") MultipartFile file,HttpSession httpSession,HttpServletRequest request){
		try {
			User user = (User) httpSession.getAttribute("user");
			InputStream is =  file.getInputStream();
			user.setPicture(FileUtil.getBytes(is));
//			userService.uploadPicture(user);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return  "redirect:userIndex";
	}
	
	
	@RequestMapping("showPicture")
	public void showPicture(@RequestParam("id")Integer id,HttpServletResponse response) throws IOException{
	User user =	userService.selectByPrimaryKey(id);
	byte[] data = user.getPicture();
	response.setContentType("image/jpg");
	response.setCharacterEncoding("utf-8");
	OutputStream os = response.getOutputStream();
	InputStream is = new ByteArrayInputStream(data);
	int len = 0;
	byte[] b = new byte[1024];
	while((len = is.read(b)) != -1){
		os.write(b, 0, len);
	}
	os.close();
	is.close();
}
	
	/**
	 *个人资料
	 */
	@RequestMapping("personData")
	public String personData(HttpSession httpSession,HttpServletRequest request){
		return  rootPath+"user/personData";
	}
	
	/**
	 *个人动态
	 */
	@RequestMapping("personDynamic")
	public String personDynamic(HttpSession httpSession,HttpServletRequest request){
		return  rootPath+"user/personDynamic";
	}
	
	/**
	 *个人心情
	 */
	@RequestMapping("personMood")
	public String personMood(HttpSession httpSession,HttpServletRequest request){
		return  rootPath+"user/personMood";
	}
	
	
	/**
	 *修改密码页面
	 */
	@RequestMapping("updatePwd")
	public String updatePwd(HttpSession httpSession,HttpServletRequest request){
		return  rootPath+"user/updatePwd";
	}
	
	/**
	 *修改密码保存
	 */
	@RequestMapping("updatePwdSave")
	@ResponseBody
	public JsonObj updatePwdSave(User user){
		JsonObj msgJson = new JsonObj();
		String pwd = MD5.md5(MD5.md5(user.getPassword()));
		user.setPassword(pwd);
		boolean success =  userService.updatePwd(user);
		String msg = "";
		if(success){
			msg = "密码修改成功!";
		}else{
			msg = "密码修改失败!";
		}
		msgJson.setMessage(msg);
		msgJson.setSuccess(success);
		return msgJson;
	}
	
	/**
	 *修改密码页面
	 */
	@RequestMapping("collectAticle")
	public String collectAticle(HttpSession httpSession,HttpServletRequest request){
		User user = (User) httpSession.getAttribute("user");
		List<ArticleCollect> collects =  articleCollectService.list(user.getId());
		request.setAttribute("collects", collects);
		return  rootPath+"user/updatePwd";
	}
	
	/**
	 * 签到
	 */
	@RequestMapping("sign")
	@ResponseBody
	public String sign(HttpSession session){
		User user = (User) session.getAttribute("user");
		SignIn record = new SignIn();
		record.setUserId(user.getId());
		record.setCreateDate(new Date());
		SignIn s = signInService.selectByUserId(record);
		if(s != null){
			return "{\"success\":\"false\"}";
		}else{
			signInService.insertSelective(record);
			user.setIntegral(user.getIntegral()+1);
			userService.updateByPrimaryKeySelective(user);
			//积分收入增加记录
			IntegralIncome income = new IntegralIncome();
			income.setCreateDate(new Date());
			income.setIntegral(1);
			income.setUserId(user.getId());
			income.setSource(1);
			incomeService.insertSelective(income);
			return "{\"success\":\"true\"}";
		}
	}
	
	/**
	 *扫码支付完毕后
	 */
	@RequestMapping("payMoneyBack")
	@ResponseBody
	public JsonObj payMoneyBack(Integer userId){
		JsonObj msgJson = new JsonObj();
		User user = userService.selectByPrimaryKey(userId);
		boolean success = false;
		if(user.getDisabled() == 0){//判断账号是否被冻结，防止恶意操作
			msgJson.setMessage(Constant.FAIL_FREEZE_MSG);
		}else{
			success =  userService.updateByPrimaryKeySelective(user);
			if(success){
				msgJson.setMessage(Constant.SUCCESS_PAY_MSG);
			}else{
				msgJson.setMessage(Constant.SUCCESS_PAY_MSG);
			}
		}
		msgJson.setSuccess(success);
		return msgJson;
	}
	
	
	
}
